<?php

class Tree extends CActiveRecord
{
	private static $_items=array();
	
	/**
	 * Returns the static model of the specified AR class.
	 * @return Product the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{tree}}';
	}

	public function i18nLanguages()
	{
		return array('en','zh');
	}
 
	public function i18nAttributes()
	{
		return array('title','content');
	}
	
    public function behaviors()
    {
        return array(
            'TreeBehavior' => array(
                'class' => 'application.extensions.nestedset.TreeBehavior'
            )
        );
    }

	public function rules()
	{
		return array(
			array('name', 'required'),
		);
	}

    public function getLevelTree($returnrootnode = true)
    {
        // Fetch the flat tree
        $rawtree = $this->getTree($returnrootnode);
		foreach($rawtree as $key => $tmp)
		{
			if($tmp->level > 2)
			{
				$tmp['name'] = '  |-'. $tmp->name;
			}
			$data[$key] = $tmp;
		}
		return $data;
    }

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'name' => '���',
		);
	}
	/**
	 * Returns the items for the specified type.
	 * @param string item type (e.g. 'PostStatus').
	 * @return array item names indexed by item code. The items are order by their position values.
	 * An empty array is returned if the item type does not exist.
	 */
	public static function items($type)
	{
		if(!isset(self::$_items[$type]))
			self::loadItems($type);
			

		return self::$_items[$type];
	}

	/**
	 * Returns the item name for the specified type and code.
	 * @param string the item type (e.g. 'PostStatus').
	 * @param integer the item code (corresponding to the 'code' column value)
	 * @return string the item name for the specified the code. False is returned if the item type or code does not exist.
	 */
	public static function item($type,$code)
	{
		if(!isset(self::$_items[$type]))
			self::loadItems($type);
		return isset(self::$_items[$type][$code]) ? self::$_items[$type][$code] : false;
	}

	/**
	 * Loads the lookup items for the specified type from the database.
	 * @param string the item type
	 */
	private static function loadItems($type)
	{
		$array = array(
			'root'=>1,
			'article'=>2,
			'pic'=>3,
			'ad'=>4,
			'links'=>5,
		);
		$pk = $array[$type];

		$root = self::model()->findByPk($pk);
		$models = $root->getChildNodes();
		self::$_items[$type] = array();
		foreach($models as $model)
		{
			$id = $model->getPrimaryKey();
			self::$_items[$type][$id]=$model['name'];
		}	
	}		

	public function getCategoryName()
	{
		return $this->name;	
	}
}
